<?php
declare(strict_types=1);

namespace App\Lib;

use Hyperf\HttpServer\Contract\ResponseInterface;

/**
 * 导出csv格式
 * Class ExportCsv
 *
 * $obj = make(ExportCsv::class);
 *      $obj->exportHead(['人名','年龄','num']);
 *      $obj->exportBody([['name'=>'张三','age'=>10,'num'=>1],['name'=>'李四','age'=>10,'num'=>1],['name'=>'王五','age'=>10,'num'=>1]]);
 *       $obj->exportBody([['name'=>'路人甲','age'=>10,'num'=>1],['name'=>'路人乙','age'=>10,'num'=>1]]);
 *      return $obj->export();
 */
class ExportCsv
{
    protected $exportDir = BASE_PATH.'/execl/export/';

    protected $response;

    protected $fp;

    protected $file;

    public function __construct(ResponseInterface $response)
    {
        $this->response = $response;
    }
    //导出
    public function export($name = 'filename.csv')
    {
        fclose($this->fp);
        return $this->response->download($this->file, $name);
    }
    //打开文件
    public function opendFile()
    {
        $this->createDir();
        $this->delDir();
        $this->file = $this->exportDir . uniqid() .'.csv';
        try {
            $this->fp = fopen($this->file, 'w+b');
        } catch (\Throwable $t) {
            throw new \Exception($t->getMessage());
        }
    }

    //删除目录
    public function delDir()
    {
        $files = scandir($this->exportDir);
        foreach ($files as $v) {
            if ($v != '.' && $v != '..') {
                $file=$this->exportDir.'/'.$v;
                unlink($file);
            }
        }
    }

    //创建目录
    public function createDir()
    {
        if (!is_dir($this->exportDir)) {
            \mkdir($this->exportDir, 0777, true);
        }
    }
    //导出头
    public function exportHead($head = [])
    {
        $this->opendFile();
        foreach ($head as $i => $v) {
            // CSV的Excel支持GBK编码，一定要转换，否则乱码
            $head[$i] =iconv("utf-8", "gb2312//IGNORE", strval($v));
        }
        fputcsv($this->fp, $head);
    }
    //导出主体数据
    public function exportBody($data = [])
    {
        foreach ($data as $v) {
            foreach ($v as $ii => $vv) {
                $v[$ii] = iconv("utf-8", "gb2312//IGNORE", strval($vv));
            }
            fputcsv($this->fp, $v);
        }
    }
}
